/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.testingProject.view;

import java.awt.Container;
import java.util.Collection;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import org.colswe.testingProject.control.AuthenticationControl;
import org.colswe.testingProject.control.SystemRolesControl;
import org.colswe.testingProject.control.SystemUserControl;
import org.colswe.testingProject.entity.SystemRoles;
import org.colswe.testingProject.entity.SystemUser;

/**
 *
 * @author andres
 */
public class SystemUserEdit extends javax.swing.JPanel {

    private SystemUser toEdit;

    /**
     * Creates new form SystemUserEdit
     */
    public SystemUserEdit(SystemUser toEdit) {
        initComponents();
        this.toEdit = toEdit;
        if (toEdit != null) {
            txtUserName.setText(toEdit.getUserName());
            cmbRole.setSelectedItem(toEdit.getUserRole().getName());
            txtUserName.setEditable(false);
        }
    }

    private ComboBoxModel generateModel() {
        Collection<SystemRoles> roles = new SystemRolesControl().readAll();
        String[] data;
        data = new String[roles.size()];
        int i = 0;
        for (SystemRoles sr : roles) {
            data[i] = sr.getName();
            i++;
        }
        return new DefaultComboBoxModel(data);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPass1 = new javax.swing.JPasswordField();
        lbl = new javax.swing.JLabel();
        txtPass2 = new javax.swing.JPasswordField();
        cmbRole = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        btnAccept = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(730, 650));
        setMinimumSize(new java.awt.Dimension(730, 650));

        jLabel1.setText("Usuario");

        jLabel2.setText("Contraseña");

        lbl.setText("Confirmación");

        cmbRole.setModel(generateModel());

        jLabel3.setText("Rol");

        btnAccept.setText("Aceptar");
        btnAccept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAcceptActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancelar");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPass1)
                            .addComponent(txtUserName)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbl)
                            .addComponent(jLabel3)
                            .addComponent(btnAccept))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnCancel)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(cmbRole, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(0, 0, Short.MAX_VALUE))
                                .addComponent(txtPass2)))))
                .addContainerGap(380, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPass1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl)
                    .addComponent(txtPass2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbRole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAccept)
                    .addComponent(btnCancel))
                .addContainerGap(425, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAcceptActionPerformed
        AuthenticationControl auth = new AuthenticationControl();
        String password1, password2, userName;
        password1 = new String(txtPass1.getPassword());
        password2 = new String(txtPass2.getPassword());
        userName = txtUserName.getText().toLowerCase();
        boolean flagN = auth.userNameUniquenessValidation(new SystemUser(userName, null));
        boolean flagP = auth.passwordValidation(password2);
        boolean flagPC = auth.passwordConfirmationValidation(password1, password2);
        boolean flagNF = auth.userNameValidation(userName);
        if (toEdit == null) {
            try {
                if (!flagP) {
                    throw new Exception("La contraseña debe tener entre 5 "
                            + "y 30 caracteres, al menos una mayúscula, una minúscula y un número");
                }
                if (!flagPC) {
                    throw new Exception("Las contraseñas no coinciden");
                }
                if (!flagN) {
                    throw new Exception("El nombre de usuarios ya es usado, seleccione otro");
                }
                if (!flagN) {
                    throw new Exception("El nombre debe tener entre 5 y 20 caracteres y no debe tener espacios");
                }
                SystemUser toCreate = new SystemUser(userName, password1);
                for (SystemRoles sr : new SystemRolesControl().readAll()) {
                    if (sr.getName().equals(cmbRole.getSelectedItem())) {
                        toCreate.setUserRole(sr);
                    }
                }
                if (new SystemUserControl().create(toCreate)) {
                    JOptionPane.showMessageDialog(this, "Creado exitosamente", "Información", JOptionPane.INFORMATION_MESSAGE);
                    Container c = getParent();
                    c.setVisible(false);
                    c.removeAll();
                    c.add(new UserAdministration());
                    c.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(this, "No se ha podido completar la operación", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            try {
                if (!flagP) {
                    throw new Exception("La contraseña debe tener entre 5 "
                            + "y 30 caracteres, al menos una mayúscula, una minúscula y un número");
                }
                if (!flagPC) {
                    throw new Exception("Las contraseñas no coinciden");
                }
                toEdit.setPassword(new String(txtPass1.getPassword()));
                if (new SystemUserControl().update(toEdit)) {
                    JOptionPane.showMessageDialog(this, "Actualizado exitosamente", "Información", JOptionPane.INFORMATION_MESSAGE);
                    Container c = getParent();
                    c.setVisible(false);
                    c.removeAll();
                    c.add(new UserAdministration());
                    c.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(this, "No se ha podido completar la operación", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnAcceptActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        Container c = getParent();
        c.setVisible(false);
        c.removeAll();
        c.add(new UserAdministration());
        c.setVisible(true);
    }//GEN-LAST:event_btnCancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAccept;
    private javax.swing.JButton btnCancel;
    private javax.swing.JComboBox cmbRole;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel lbl;
    private javax.swing.JPasswordField txtPass1;
    private javax.swing.JPasswordField txtPass2;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables
}
